package top.digger.web.cron;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import top.digger.web.entity.HotSearch;
import top.digger.web.mapper.HotSearchMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Configuration
@EnableScheduling
public class BaiduHotSearchTask {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private HotSearchMapper hotSearchMapper;

    @Scheduled(cron = "0 1 * * * ?")
    public void test(){
        HttpClient httpClient = init();
        HttpGet httpGet = new HttpGet("https://top.baidu.com/board?tab=realtime");
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            String result = EntityUtils.toString(httpResponse.getEntity());
            Document doc = Jsoup.parse(result);
            Elements hotSearchS = doc.select("div.category-wrap_iQLoo");
            for (Element hotSearch : hotSearchS){
                HotSearch hotSearchEntity = new HotSearch();
                hotSearchEntity.setText(hotSearch.select("div.c-single-text-ellipsis").first().text());
                hotSearchEntity.setSummary(hotSearch.select("div.hot-desc_1m_jR").first().text());
                hotSearchEntity.setUrl(hotSearch.select("div.content_1YWBm").first().getElementsByTag("a").first().attr("href"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                hotSearchEntity.setCreateMonth(sdf.format(new Date()));
                hotSearchEntity.setHotPoint(Long.valueOf(hotSearch.select("div.hot-index_1Bl1a").first().text()));
                hotSearchMapper.insertOrUpdate(hotSearchEntity);

            }
//            System.out.println(hotSearchS);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public HttpClient init(){
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)//一、连接超时：connectionTimeout-->指的是连接一个url的连接等待时间
                .setSocketTimeout(5000)// 二、读取数据超时：SocketTimeout-->指的是连接上一个url，获取response的返回等待时间
                .setConnectionRequestTimeout(5000)
                .build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
        return httpClient;
    }


    public HttpGet get(String url, Map<String, String> params){
        if (params != null){
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()){
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            url = url + "?" + sb.toString();
        }
        HttpGet httpGet = new HttpGet(url);
        return httpGet;
    }
}
